package controller

import (
	myjwt "ip_server/jwt"
	"ip_server/service/model"
	"ip_server/util"
	"net/http"
	"time"

	"golang.org/x/crypto/bcrypt"

	"ip_server/logger"

	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

type UserController struct {
}

// 注册信息
type RegistInfo struct {
	// 手机号
	Phone string `json:"mobile"`
	// 密码
	Pwd string `json:"pwd"`
}

type Uinfo struct {
	Id           string `json:"user_id"`
	Name         string `json:"name"`
	UserName     string `json:"user_name"`
	IsAdmin      bool   `json:"is_admin"`
	AccountExist bool   `json:"account_exist"`
	CountPerPage int    `json:"count_per_page"`
	GroupID      string `json:"group_id"`
}

// LoginResult 登录结果结构
type LoginResult struct {
	Token string `json:"token"`
	User  Uinfo  `json:"user"`
}

// Login 登录
func (u *UserController) Login(c *gin.Context) {
	type Request struct {
		Username string `form:"username" url:"status" sigin:"true"`
		Pwd      string `form:"password" url:"status" sigin:"true"`
	}
	logger.Debug("-------------1111-------------------")
	logid := util.GenerateLogid()
	var loginReq Request
	if err := c.ShouldBind(&loginReq); err != nil {
		logger.Error(logid, err.Error())
		c.Set("err", err.Error())
		return
	}
	if loginReq.Username == "" || loginReq.Pwd == "" {
		logger.Error(logid, "账号密码错误")
		c.Set("err", "账号密码错误")
		return
	}
	var umodel model.User
	// 验证账号密码
	user, _ := umodel.GetInfoByName(loginReq.Username)
	if user.Id == "" {
		logger.Error(logid, "用户不存在")
		c.Set("err", "用户不存在")
		return
	}
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(loginReq.Pwd))
	if err == nil {
		generateToken(c, user)
	} else {
		logger.Error(logid, "验证失败")
		c.Set("err", "验证失败")
		return
	}
}

// generateToken 生成令牌
func generateToken(c *gin.Context, user model.User) {
	j := &myjwt.JWT{
		[]byte("newtrekWang"),
	}
	claims := myjwt.CustomClaims{
		user.Id,
		user.Name,
		user.UserName,
		user.IsAdmin,
		"",
		jwtgo.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000),    // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 36*3600), // 过期时间 一小时
			Issuer:    "newtrekWang",                      //签名的发行者
		},
	}

	token, err := j.CreateToken(claims)

	if err != nil {
		logger.Error(err.Error())
		c.Set("err", "验证失败")
		return
	}

	data := LoginResult{
		User: Uinfo{Id: user.Id, Name: user.Id, UserName: user.Id, IsAdmin: user.IsAdmin,
			AccountExist: user.AccountExist, CountPerPage: user.CountPerPage},
		Token: token,
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  0,
		"message": "登录成功！",
		"data":    data,
	})
	return
}

// Signout 登出接口
func (u *UserController) Signout(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status":  0,
		"message": "成功",
	})
}

// GetDataByTime 一个需要token认证的测试接口
func (u *UserController) GetDataByTime(c *gin.Context) {
	claims := c.MustGet("claims").(*myjwt.CustomClaims)
	if claims != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":  0,
			"message": "成功",
			"data":    claims,
		})
	}
}

func (u *UserController) CommonAuth(c *gin.Context) {
	claims := c.MustGet("claims").(*myjwt.CustomClaims)
	if claims == nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 0,
			"msg":    "token失效",
			"data":   "",
		})
	}
}
